package com.imay.live.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.FrameLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.imay.live.activity.dynamics.LabelFeedsActivity;
import com.imay.live.activity.dynamics.SearchActivity;
import com.imay.live.adapter.SearchTopicAdapter;
import com.imay.live.analytics.MobclickAgent;
import com.imay.live.model.SearchTopicModel;
import com.imay.live.proto.Result;
import com.imay.live.proto.helper.ProtoCallBack;
import com.imay.live.proto.helper.ProtoHttpFactory;
import com.imay.live.proto.helper.ProtoRequestHelper;
import com.imay.live.view.custom.LoadRefreshViewControl;
import com.imay.live.view.recyclerview.WrapContentLinearLayoutManager;
import com.imay.live.R;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;

import java.util.ArrayList;

/**
 * Created by lzx on 2017/05/03 0003.
 * 搜索话题
 */

public class SearchTopicFragment extends BaseRequestFragment {
    private RecyclerView mrecyclerView;
    private ArrayList<MultiItemEntity> mdatas;
    private SearchTopicAdapter mAdapter;
    private FrameLayout container;
    private LoadRefreshViewControl loadViewControl;
    private String name;
    private int count = 5;

    public static SearchTopicFragment newInstance() {
        return new SearchTopicFragment();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.searchuser_layout;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        container = $(R.id.container);


        mdatas = new ArrayList<MultiItemEntity>();
        mAdapter = new SearchTopicAdapter(mdatas);

        loadViewControl = new LoadRefreshViewControl(getContext(), mAdapter, count);
        mrecyclerView = loadViewControl.addLoadView(container, new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
//                refreshLayout.finishRefreshing();
            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                moreLoad(mAdapter.getData().size(), name);
            }
        },false);
        mrecyclerView.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                MobclickAgent.onEvent(getActivity(),"search_result_topic");
                if (view.getId() == R.id.tv_topic_info) {
                    SearchTopicModel searchTopicModel = (SearchTopicModel) adapter.getItem(position);
                    LabelFeedsActivity.startActivity(getActivity(), searchTopicModel.getLabelContent());
                }
            }
        });
        mrecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                ((SearchActivity) getActivity()).setDefault();
            }
        });
        WrapContentLinearLayoutManager wrapContentLinearLayoutManager
                = new WrapContentLinearLayoutManager(getActivity());
        mrecyclerView.setLayoutManager(wrapContentLinearLayoutManager);
        mrecyclerView.setHasFixedSize(true);

        mrecyclerView.setAdapter(mAdapter);
        refreshLoad();
    }

    public void searchTopic(String name) {
        this.name = name;
        refreshLoad(name);
    }

    private void refreshLoad() {
        loadViewControl.setError(getResources().getString(R.string.search_topicerror));
        loadViewControl.refreshLoadView(null, 0);
    }


    private void moreLoad(int index, String name) {
        ProtoRequestHelper.task(ProtoHttpFactory.getsearchlabelList(index, name, count)).setTag(this.hashCode()).request(new ProtoCallBack() {
            @Override
            public void onRequestSuccess(String command, String data) {
                try {
                    Result<ArrayList<SearchTopicModel>> result = JSON.parseObject(data, new TypeReference<Result<ArrayList<SearchTopicModel>>>() {
                    }.getType());
                    loadViewControl.moreLoadView(result.data, result.result);
                } catch (Exception e) {
                    loadViewControl.loadError(getResources().getString(R.string.search_topicresult));
                }
            }

            @Override
            public void onRequestError(String command, int code, String message) {
                loadViewControl.loadError(getResources().getString(R.string.search_topicresult));

            }
        });
    }

    private void refreshLoad(String name) {
        loadViewControl.setError(getResources().getString(R.string.search_topicresult));
        ProtoRequestHelper.task(ProtoHttpFactory.getsearchlabelList(0, name, count)).setTag(this.hashCode()).request(new ProtoCallBack() {
            @Override
            public void onRequestSuccess(String command, String data) {
                try {
                    Result<ArrayList<SearchTopicModel>> result = JSON.parseObject(data, new TypeReference<Result<ArrayList<SearchTopicModel>>>() {
                    }.getType());
                    loadViewControl.refreshLoadView(result.data, result.result);
                } catch (Exception e) {
                    loadViewControl.loadError(getResources().getString(R.string.search_topicresult));
                }
            }

            @Override
            public void onRequestError(String command, int code, String message) {
                loadViewControl.loadError(getResources().getString(R.string.search_topicresult));

            }
        });
    }
    boolean isCreated;
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isCreated = true;
    }
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        // 友盟统计页面跳转，重写此方法，可以保证ViewPager切换Fragment时能够准确的记录Fragment之间的跳转
        // 不用再调用Fragment的生命周期方法
        if (isCreated){
            if (isVisibleToUser) {
                MobclickAgent.onEvent(getActivity(),"search_topic");
                MobclickAgent.onPageStart(getClass().getSimpleName());
            } else {
                MobclickAgent.onPageEnd(getClass().getSimpleName());
            }
        }
    }
}
